/*
 * Copyright (c) 2011, Eriq Muhammad Adams J.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of the Institute Technology of Sepuluh Nopember nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY ERIQ MUHAMMAD ADAMS J. ``AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
package com.googlecode.pathmachine.ui.renderer.impl;

import com.googlecode.pathmachine.mm.MinimalSectorAbstraction;
import com.googlecode.pathmachine.mm.Point2D;
import com.googlecode.pathmachine.mm.Point3D;
import com.googlecode.pathmachine.mm.TempEdgeData;
import com.googlecode.pathmachine.ui.renderer.MinimalSectorAbstractionRenderer;
import com.jme3.asset.AssetManager;
import com.jme3.material.Material;
import com.jme3.math.ColorRGBA;
import com.jme3.scene.Geometry;
import com.jme3.scene.Mesh;
import com.jme3.scene.Node;
import com.jme3.scene.debug.Grid;
import com.jme3.scene.shape.Box;
import java.util.ArrayList;
import java.util.List;
import jme3tools.optimize.GeometryBatchFactory;

/**
 *
 * @author <a href="mailto:eriq.adams@gmail.com">Eriq Muhammad Adams J.</a> 
 */
public class MinimalSectorAbstractionRendererImpl implements MinimalSectorAbstractionRenderer {

    private ColorRGBA edgeColor = ColorRGBA.Green;
    private ColorRGBA sectorColor = ColorRGBA.Blue;
    private ColorRGBA regionColor = ColorRGBA.Red;

    public Node render(MinimalSectorAbstraction msa, AssetManager assetManager) {
        Node node = new Node("msaDebugShape");

        // Draw Sector Grids
        Grid grid = new Grid(msa.getNumYSectors() + 1, msa.getNumXSectors() + 1, msa.getMap().getTileSize() * msa.getSectorSize());
        grid.setLineWidth(4);
        Geometry gridGeom = new Geometry("msaDebugGeom", grid);
        Material mat = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md");
        mat.getAdditionalRenderState().setWireframe(false);
        mat.setColor("Color", sectorColor);
        gridGeom.setMaterial(mat);
        Point3D p = msa.getMap().getOpenGLCoord(0, 0);
        gridGeom.setLocalTranslation(p.x - msa.getMap().getTileSize() / 2, p.y + 0.01f,
                p.z - msa.getMap().getTileSize() / 2);
        node.attachChild(gridGeom);

        // adding point and region box
        // calculate number of lines
        List<Point3D> startPoints = new ArrayList<Point3D>();
        List<Point3D> endPoints = new ArrayList<Point3D>();
        List<Geometry> regionGeoms = new ArrayList<Geometry>();
        for (int x = 0; x < msa.getSectors().size(); x++) {
            for (int y = 0; y < msa.getSectors().get(x).numRegions; y++) {
                List<TempEdgeData> neighbors = new ArrayList<TempEdgeData>();
                msa.getNeighbors(x, y, neighbors);
                Point2D ploc = msa.getXYLocation(x, y);
                Point3D p3d = msa.getMap().getOpenGLCoord(ploc.x, ploc.y);
                float xx = p3d.x;
                float yy = p3d.y;
                float zz = p3d.z;

                // Draw regions 
                float size = 0.05f;
                Box regionBox = new Box(size, size, size);
                Geometry regionGeom = new Geometry("reg", regionBox);
                regionGeom.setLocalTranslation(xx, yy + size, zz);
                regionGeoms.add(regionGeom);

                // Define startPoints and endPoints for abstraction edges
                for (int z = 0; z < neighbors.size(); z++) {
                    switch (neighbors.get(z).direction) {
                        case 0:
                            addPoints(startPoints, endPoints, msa,
                                    x - msa.getNumXSectors(), neighbors.get(z).to, p3d);
                            break;
                        case 1:
                            addPoints(startPoints, endPoints, msa,
                                    x + 1, neighbors.get(z).to, p3d);
                            break;
                        case 2:
                        case 3:
                            break;
                        case 4:
                            addPoints(startPoints, endPoints, msa,
                                    x - msa.getNumXSectors() + 1, neighbors.get(z).to, p3d);
                            break;
                        case 5:
                            addPoints(startPoints, endPoints, msa,
                                    x + msa.getNumXSectors() + 1, neighbors.get(z).to, p3d);
                            break;
                        default:
                            break;
                    }
                }
            }
        }

        // Merge region geoms to single region mesh
        Mesh regionMesh = new Mesh();
        GeometryBatchFactory.mergeGeometries(regionGeoms, regionMesh);
        regionGeoms.clear();
        regionGeoms = null;
        Material regionMat = mat.clone();
        regionMat.setColor("Color", regionColor);
        Geometry regionGeom = new Geometry("region", regionMesh);
        regionGeom.setMaterial(regionMat);
        node.attachChild(regionGeom);

        // Draw Abstraction Edges
        Edges edges = new Edges(startPoints, endPoints);
        edges.setLineWidth(4);
        Material edgesMat = mat.clone();
        edgesMat.setColor("Color", edgeColor);
        Geometry edgesGeom = new Geometry("edges", edges);
        edgesGeom.setMaterial(edgesMat);
        edgesGeom.move(0f, +0.01f, 0f);
        node.attachChild(edgesGeom);
        startPoints = null;
        endPoints = null;

        return ((Node) GeometryBatchFactory.optimize(node));
    }

    private void addPoints(List<Point3D> startPoints, List<Point3D> endPoints, MinimalSectorAbstraction msa, int sector, int region, Point3D sp) {
        Point2D p2d = msa.getXYLocation(sector, region);
        if (p2d != null) {
            Point3D pGL = msa.getMap().getOpenGLCoord(p2d.x, p2d.y);
            startPoints.add(sp);
            endPoints.add(pGL);
        }
    }

    /**
     * @param edgeColor the edgeColor to set
     */
    public void setEdgeColor(ColorRGBA edgeColor) {
        this.edgeColor = edgeColor;
    }

    /**
     * @param sectorColor the sectorColor to set
     */
    public void setSectorColor(ColorRGBA sectorColor) {
        this.sectorColor = sectorColor;
    }

    /**
     * @param regionColor the regionColor to set
     */
    public void setRegionColor(ColorRGBA regionColor) {
        this.regionColor = regionColor;
    }
}
